9643. Catalan numbers

 

Catalan numbers cn are defined by the recurrence relation:

ñ0 = 1,

ñn = , n > 0

Compute the n-th Catalan number modulo m.

 

Input. Two integers n (0 ≤ n ≤ 104) and m (0 < m ≤ 109).

 

Output. Print the value of cn mod m.

 

Sample input

Sample output

5 100

42

 

 

SOLUTION

Catalan numbers

 

Algorithm analysis

Let’s rewrite the recurrence relation as follows:

ñ0 = 1,

ñn = c0cn-1 + c1cn-2 + c2cn-3 + ... + cn-1c0, if n > 0

For example,

·        ñ0 = 1

·        ñ1 = c0c0  = 1,

·        ñ2 = c0c1 + c1c0 = 1 + 1 = 2,

·        ñ3 = c0c2 + c1c1 + c2c0 = 2 + 1 + 2 = 5,

·        ñ4 = c0c3 + c1c2 + c2c1 + c3c0 = 5 + 2 + 2 + 5 = 14,

·        ñ5 = c0c4 + c1c3 + c2c2 + c3c1 + c4c0 = 14 + 5 + 4 + 5 + 14 = 42

Since the value of ñn is computed based on all previous values c0, c1, c2, ..., cn-1, we will store the Catalan numbers in a linear array.

 

Algorithm implementation

Declare an array cat, where we’ll store the Catalan numbers: cat[i] = ci.

 

long long cat[10001];

 

Read the input data.

 

scanf("%lld %lld", &n, &m);

 

Compute the Catalan numbers using the recurrence relation.

 

cat[0] = 1;

for (i = 1; i <= n; i++)

{

  for (j = 0; j < i; j++)

    cat[i] = (cat[i] + cat[j] * cat[i - j - 1]) % m;

}

 

Print the n-th Catalan number.

 

printf("%lld\n", cat[n]);

 

Python implementation

Read the input data.

 

n, m = map(int, input().split())

 

Store the values of the Catalan numbers in the list cat, where cat[i] = ci.

 

cat = [0] * (n + 1)

 

Compute the Catalan numbers using the recurrence relation.

 

cat[0] = 1

for i in range(1, n + 1):

  for j in range(i):

    cat[i] = (cat[i] + cat[j] * cat[i - j - 1]) % m

 

Print the n-th Catalan number.

 

print(cat[n])